//
//  API_Chat.swift
//  WalkNovel
//
//  Created by Kevin on 19/2/2023.
//

import UIKit
import Moya

enum API_Chat {
    /// 聊天
    case GPTChat(String)
    /// 图片
    case GPTImage(String)
}

let chat_timeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<API_Chat>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 5
        done(.success(request))
    }catch {
        return
    }
}

let provider_Chat = MoyaProvider<API_Chat>(requestClosure: chat_timeoutClosure)

extension API_Chat: TargetType {
    
    var baseURL: URL {
        return URL(string: "https://api.openai.com/v1")!
    }
    
    var path: String {
        switch self {
        case .GPTChat(_):
            return "/chat/completions"
        case .GPTImage(_):
            return "/images/generations"
        }
    }
    
    var method: Moya.Method {
        return .post
    }
    
    var parameterEncoding: ParameterEncoding {
        return JSONEncoding.default
    }
    
    var sampleData: Data {
        return "test".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        var ps = [String: Any]()
        switch self {
        case .GPTChat(let prompt):
            ps["model"] = "gpt-3.5-turbo"
            var msg = [String: String]()
            msg["role"] = "user"
            msg["content"] = prompt
            ps["messages"] = [msg]
            return .requestParameters(parameters: ps, encoding: JSONEncoding.default)
        case .GPTImage(let prompt):
            ps["prompt"] = prompt
            ps["n"] = 1
            ps["size"] = "1024x1024"
            return .requestParameters(parameters: ps, encoding: JSONEncoding.default)
        }
    }
    
    var headers: [String : String]? {
        return ["content-type": "application/json", "Authorization": "Bearer \(WNConfigure.ChatGPT.appKey)"]
    }
}
